DAMN = (typeof DAMN != "undefined")?  DAMN : {};

DAMN.GetContent = function(li) {
  return $($('a', li).attr('href')).data('Content');
};

DAMN.GetTab = function(tabs, index) {
  return $($('li:eq('+index+')', tabs.children('li:not(".user-tab")')).children('a').attr('href'));
};

DAMN.Content = function(name) 
{   
  this.name = name;
  this.selectedNode = null;
  self.assets = [];
  
  this.AttachTo = function(parent) {
    this.parent = parent;
    
    var cleanName = this.name.replace('.', '-').replace(' ', '-').replace('#', '-');
    cleanName = '#tabs-Content-'+ cleanName;
    parent.tabs('add', cleanName, this.name);
    this.tab = $(cleanName);
    
    this.tab.data('Content', this);
    this.tab.addClass('Content-tab');
    
    
    this.size = 4;
    this.controls = $('<div style="height: 20px;">\
                      <div class="Content-pages" style="display:none; position: relative; float:left; height:100%;/* background-color:#f00;*/">\
                        <span class="ui-icon ui-icon-triangle-1-w page-link back"></span>\
                        <span class="Content-pages-a"></span>\
                        <span style="float:right;" class="ui-icon ui-icon-triangle-1-e page-link forward"></span>\
                      </div>\
                      <div style="position: relative; float:right; ">\
                        <span size="2" class="Content-control ui-icon ui-icon-image"></span>\
                        <span size="4" class="active Content-control ui-icon ui-icon-video"></span>\
                        <span size="8" class="Content-control ui-icon ui-icon-calculator"></span></div></div>');
    this.tab.append(this.controls);
    
    var self = this;
    this.controls.find('.Content-control').each(function (){
      $(this).click(function (){
        self.size = $(this).attr('size');
        self.Resize();
        $(this).parent().children('span.active').removeClass('active');
        $(this).addClass('active');
      });
    });
    
    
    this.wrapper = $('<div class="wrapper" style="/*background-color:#f00;*/"></div>');
    var top = this.controls.position().top + this.controls.height();
    this.wrapper.css({'overflow':'hidden', 'margin':'auto', 'bottom':0, 'top':top,  'left':'0', 'right':'0','position':'absolute'});
    this.tab.append(this.wrapper);
    
    this.content = $('<div class="content" style="width: 100%;"></div>');
    this.content.css({'margin':'auto', 'bottom':'0', 'top':'0',  'left':'0', 'right':'0','position':'absolute'});
    this.wrapper.append(this.content);
    
    this.tab.bind('resize', function() {
      self.Resize();
    });

    
    this.assettemplate = $('<div id="assettemplate"><img></img></div>');
    this.assettemplate.append($('<img></img>').css({"width":'0px', "height":'0px'}));
	  this.assettemplate.addClass('asset ui-selectee ui-selecting ui-selected');
	  this.assettemplate.css({'visiblity': 'hidden', 'position': 'absolute', 'left':'-999px'});
    this.tab.append(this.assettemplate);
    
    
    $('.page-link').live('click', function() {
      if ($(this).hasClass('back')) { self.currentPage = Math.max(0, self.currentPage-1); }
      else if ($(this).hasClass('forward')) { self.currentPage += 1; }
      else if ($(this).hasClass('back-10')) { self.currentPage = Math.max(0, self.currentPage-10); }
      else if ($(this).hasClass('forward-10')) { self.currentPage += 10; }
      else { self.currentPage = Math.max(0, $(this).text()-1); }
      self.LoadPage();
		});
		
		self.lastScrollTime = new Date();
		this.wrapper.mousewheel(function (event, delta) {
		  if ((new Date() - self.lastScrollTime) > 500) {
		    var old = self.currentPage;
  		  self.currentPage = Math.max(0, self.currentPage-delta);
  		  if (old != self.currentPage) {
  		    self.LoadPage();
  		  }
  		  self.lastScrollTime = new Date();
		  }
		});

        
    
    DAMN.AssetMananger.Register("file", this.Icons.bind(this));
    
    this.closeable = true;  
    
    self.Resize(true);  
  };
		
	
  this.Resize = function(dontload)
  {
    var self = this;
    this.assetSize = (this.content.innerWidth()/this.size)-10; //TODO: where does this magic 10 come from??
    this.padding = this.assettemplate.outerWidth(true);
    
    var AssetsPerColumn = function (si) { return Math.floor(self.content.innerHeight()/(self.content.innerWidth()/si)); };
    this.totalAssetsPerPage = AssetsPerColumn(8) * 8;
    this.assetsPerPage = AssetsPerColumn(this.size) * this.size;
    
    if (!dontload) this.LoadPage();
  };
  
  this.Pages = function(len)
  {
    //Normalize page nr
    this.currentPage = Math.max(0, Math.min(this.currentPage, Math.ceil(this.total/this.assetsPerPage)-1));
    
    var c = this.controls.find('.Content-pages-a');
    c.empty();
    var tot = this.total/this.assetsPerPage;
    if (this.currentPage > 0) {
      var link = $('<a href="#" class="page-link back-10">...</a>');
      c.append(link);
    }
    var x =0; var i = this.currentPage;
    for (; i < tot && x < 10; x++, i++) {
      var link = $('<a href="#" class="page-link">'+(i+1)+'</a>');
      if (i == this.currentPage) link.addClass('active'); 
      c.append(link);
    }
    if (tot - this.currentPage > 10) {
      var link = $('<a href="#" class="page-link forward-10">...</a>');
      c.append(link);
    }
  };
  
  this.SetDataURL = function(url) {
    this.url = url;
  };
  
  this.GetData = function(b, e, cb) {
    var url = this.url;
    url += '&begin='+b+'&end='+e;
    $.getJSON(url, function(data, s, xhr){
      var count = xhr.getResponseHeader("Assets-Total-Count");
      cb({total: count, assets: data});  
    });
  };
  
  this.LoadPage = function() {
    DAMN.AssetMananger.ClearAll();
    if (!this.url) return;
    var self = this;
    //self.assets = [];
    if (self.w) self.w.running = false;
    self.content.children('.asset, .message').remove();
    
    self.content.addClass('loading');
    self.controls.find('.Content-pages').hide();
    var b = self.totalAssetsPerPage * self.currentPage;
    var e = b + self.totalAssetsPerPage;
    //document.title = b+' - '+e+' ='+self.fileid;
    if (b != self.begin || e != self.end) {   
      self.GetData(b, e, function(data){
        self.total = data.total;
        self.assets = data.assets;
        self.Pages();
        self.Work();
        self.controls.find('.Content-pages').show();    
      });
    } else {
      self.Pages();
      self.Work();
      self.controls.find('.Content-pages').show();
    }
    self.begin = b;
    self.end = e;
  };
  
  this.Work  = function() {
    var self = this;
    var b = this.currentPage * this.assetsPerPage;
    self.w = new DAMN.Content.Worker(self.assets, b, b+this.assetsPerPage, 
          function(i, d){
            var a = new DAMN.Content.Asset(d, self.content);  
            var s = self.assetSize-(self.padding/2);
            a.Resize(s, self.size);
            a.Build();
          },
          function(){
            DAMN.Content.MakeSelectable(self.content);
            self.content.removeClass('loading');
            if (self.total == 0) {
              self.content.append($('<div class="message" style="position:absolute; top:25%; left:50%; font-size: 2em; margin-left:-2em">No results</div>'));
            }
          });
  }
	
	this.Icons = function(op, el) { 
    if (op == 'SELECT') {
      this.SetDataURL('/files/'+el.attr('fileid')+'/children/assets/?');      
      this.Load(); 
    }
  };
  
  this.Load = function(op, el) { 
	//DAMN.AssetMananger.ClearAll();
    this.currentPage = 0; 
    
    this.begin = -1;
    this.end = -1;         
    
    this.LoadPage(); 
  };
  		
};

DAMN.Content.Asset = function(data, parent) {

  //this.type = 'Asset';
  this.id = data.pk;
  this.format = data.fields.format[0];
  this.type = data.fields.format[1];
  this.subName = data.fields.subName;
  this.parent = parent;
  this.element = null;
  this.size = 0;

  this.Build = function() {
    var self = this;
    if (this.element) {
      return;
    }
    this.element = $("<div>").attr({
      "class": "asset ui-selectee loading",
      "size": this.assetsPerPage,
      "title": this.subName
    }).css({
      'width': this.size+'px',
      'height': this.size+'px'
    }).append('<span class="format">'+(this.type?this.type:this.format)+'</span>');
    this.element.data('assetid', this.id);
    this.element.data('src_format', this.format);
    this.element.data('type', this.type);
    this.parent.append(this.element);
    this.element.DAMNPreview({imageonly: true});
  };

  this.Resize = function(size, assetsPerPage) { 
    this.size = size;
    this.assetsPerPage = assetsPerPage;
    if (this.element) {
      this.element.attr('size', this.assetsPerPage);
      this.element.DAMNPreview('size', {'width':this.size, 'height':this.size});
    }
  };

  this.Destruct = function() {
    if (this.element == null) {
      return;
    }
    this.element.remove();
    this.element = null;
  };

};



DAMN.Content.MakeSelectable = function(target)
{
  //DAMN.AssetMananger.ClearAll();
  target.selectable( "destroy" );
  target.selectable({ 
      selected: function(event, ui) 
          {
            //Ignore if already selected.
            if (!$(ui.selected).hasClass('DAMN-selected')) {
                DAMN.AssetMananger.FireOnSelection($(ui.selected), 'asset');
              $(ui.selected).addClass('DAMN-selected');
            }
          },
      unselected: function(event, ui) 
          {
              DAMN.AssetMananger.FireOnUnSelection($(ui.unselected), 'asset');
              $(ui.unselected).removeClass('DAMN-selected');
          },
      filter: '.asset' });
};

DAMN.Content.Worker = function(data, begin, end, onData, onDone) {
  this.data = data;
  this.onData = onData;
  this.onDone = onDone;
  this.index = begin;
  this.end = end;
  this.running = true;
  
  this.run = function() { 
    if (!this.running) return;
    if(this.index < Math.min(this.data.length, this.end)){
      onData(this.index, this.data[this.index]);
      this.index++;
      setTimeout( function(self){self.run();}, 50 , this);
    }
    else if (onDone) {
      this.running = false;
      onDone();
    }
    else {
      DAMN.Log.debug('DAMN.Content.Worker: finished with no onDone callback.');
    }
  };
  
  this.run();
};
